package pers.xukai.common.config.autoConfig.exceptionAdvice;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import pers.xukai.common.constant.GlobalConstant;
import pers.xukai.common.constant.response.ResponseEnum;
import pers.xukai.common.constant.response.ResponseResult;
import pers.xukai.common.exception.BizException;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 异常处理器
 *
 * @author 殷绪凯
 * @datetime 2022年 11月 29日 22:37
 */
@RestController
@ControllerAdvice
@Slf4j
public class ExceptionAdvice {

    /**
     * 项目异常（已知且手动抛出的异常）
     *
     * @param e 业务异常
     * @return 错误响应
     */
    @ResponseBody
    @ExceptionHandler(BizException.class)
    public ResponseResult<Object> handleBizException(BizException e) {
        return ResponseResult.voidResponse(
                e.getMessage(),
                ObjectUtil.isNull(e.getCode()) ? GlobalConstant.ERROR_CODE : e.getCode()
        );
    }

    @ResponseBody
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ResponseResult<Object> constraintException(SQLIntegrityConstraintViolationException e){
        String message = e.getMessage();
        String errMsg = message.substring(message.indexOf("'"), message.indexOf("'", message.indexOf("'")+1));
        log.info(String.format("【%s】存在重复值！",errMsg));
        return ResponseResult.voidResponse(
//                String.format("【%s】存在重复值！",errMsg),
                "请勿重复提交哦",
                ResponseEnum.COMMONERROR.getCode()
        );
    }
}
